package com.scalar.chiptrack.operations.packingslip.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.packingslip.dao.NewPackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.dao.PackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.forms.PackingSlipForm;
import com.scalar.chiptrack.operations.packingslip.forms.SendMailForm;
import com.scalar.chiptrack.operations.packingslip.forms.ShippingAdviseForm;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.sales.ContactPerson;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.NewSalesOrderDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.StringUtils;


public class SendMailAction extends ChipTrackAction {

	public SendMailAction() {

	}

	public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response )
	{
		HashMap info 		     = new HashMap();
		HashMap errors 		     = new HashMap();
		boolean success 	     = false;
		HttpSession session      = request.getSession();
        //ArrayList contactPersons = null;
        String action		     = request.getParameter( "action" );
        String vendorInterface = (String) request.getAttribute( "isFromTrackingNoPage" );
        String vendorMailAttachmentType = request.getParameter( "vendorMailAttachmentType" );
		int customerShippingId = -1;

        ArrayList psContactPersons = null;
        ArrayList psVendorContactPersons = null;
        String types[] = null;
        String vtypes[] = null;
        int notificationUserEmailsLength = 0;
		User user = (User) session.getAttribute ( SessionKeys.USER_KEY );

        if ( ( vendorInterface != null ) && ( vendorInterface.equals( "true" ) ) ) //when request comes from PS Vendor Interface
        {
            action =  (String) request.getAttribute( "action" );
        }
        if ( vendorMailAttachmentType != null ) //when request comes from PS Vendor Interface
        {
            request.setAttribute("vendorMailAttachmentType", request.getParameter("vendorMailAttachmentType") );
        }

		if ( user == null )
		{
            request.setAttribute ( "closeWindowAfterSessionExp", "true" );
			return ( mapping.findForward( "success" ) );
		}

		request.setAttribute( SessionKeys.INFO_MESSAGES, info );
		request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
		request.setAttribute( "customerShippingId", request.getParameter( "customerShippingId" ) );
		request.setAttribute( "salesOrderId", request.getParameter( "salesOrderId" ) );
        request.setAttribute( "locationId", request.getParameter( "locationId" ) );

        SendMailForm sendMailForm = ( SendMailForm ) form;

		String mineType = sendMailForm.getAttachMIMEType();

		if ( ( mineType == null ) || ( mineType.trim().length() == 0  ) )
		{
			mineType = "PDF";
			sendMailForm.setAttachMIMEType( "PDF" );
		}

		try
		{
			customerShippingId = Integer.parseInt ( (String) request.getParameter ( "customerShippingId" ) );
		}
		catch (NumberFormatException nfe) {
			errors.put( "Could not fetch the Packing Slip Information", null );
		}

		if( ( action != null ) && ( action.equalsIgnoreCase( "save" ) ) )
		{
            String recipientType = sendMailForm.getRecipientType();

			if ( customerShippingId != -1 )
			{
				PackingSlipForm packingSlipForm = null;

				try
				{
                    packingSlipForm = new PackingSlipForm();
                    packingSlipForm.setCustomerShippingId( customerShippingId );
                    if ( NewPackingSlipDAO.isSoftWarePackingSlip(packingSlipForm) )
                    {
                    	return ( mapping.findForward( "swSendMail" ) );
                    }
                    else
                    {
					    packingSlipForm = NewPackingSlipDAO.loadPackingSlipById ( customerShippingId );
                    }
                    packingSlipForm.setRecipientType( recipientType );
					success = true;
				}
				catch ( ScalarException se )
				{
					errors.put ( "Internal Server Error", "Could not load Packing Slip" );
				}

				if( success == true )
				{
					request.setAttribute ( "packingSlipForm", packingSlipForm );
					try
					{
						NewPackingSlipAction packingSlipAction = new NewPackingSlipAction();
						String host 			= ConfigManager.getChipTracHost();
						String packingSlipFile 	= null;

						String from = ConfigManager.getFromEmailId(Constants.FROM_EMAIL_PACKINGSLIP_GROUP_NAME );

                        String to 	= StringUtils.concatStrings( sendMailForm.getToUsers(), Mailer.EMAIL_SEPARATOR );
						String cc 	= StringUtils.concatStrings( sendMailForm.getCcUsers(), Mailer.EMAIL_SEPARATOR );
						String bcc 	= StringUtils.concatStrings( sendMailForm.getBccUsers(), Mailer.EMAIL_SEPARATOR );

                        if( cc == null || cc.trim().length() == 0 )
                        {
                            sendMailForm.setCcUsers ( null );
                        }
                        if( bcc == null || bcc.trim().length() == 0 )
                        {
                            sendMailForm.setBccUsers ( null );
                        }

						String subject = sendMailForm.getSubject();

						String message = null;
                        int cstRandKey = -1;

						if( ( message = ( String) request.getAttribute( "shipAlertMessage" ) ) == null )
						{
							if( !( packingSlipForm.getStatus().equalsIgnoreCase("CANCELLED") || packingSlipForm.getStatus().equalsIgnoreCase("SHIPPED") ) )
							{
								message = "<font size=3>";
								message += sendMailForm.getMessage().replaceAll( "\n", "<br>" );
                                cstRandKey = packingSlipForm.getCstRandomKey();

                                if( "vendor".equalsIgnoreCase( packingSlipForm.getRecipientType() ) )
                                {
                                    if( ConfigManager.isVendorFacingAllowedForshipping() )
                                    {
                                        message += "<br>Click <a target='_blank' href=http://" + host + "/" + ConfigManager.getChipTracContext() + "/shippingAdvise.do?ps=" + customerShippingId + "&cstKey=" + cstRandKey +">here</a> to update the tracking number, No. Of Boxes, Total Weight etc, and to send the Shipment Notification.";
                                    }
                                }
								message += "</font>";
							}
							else
							{
								message = "<font size=3>";
								message += sendMailForm.getMessage().replaceAll( "\n", "<br>" );
								message += "</font>";
							}
						}

                        if( ( vendorInterface == null  ||  vendorInterface.equals( "true" ) == false ) && ( vendorMailAttachmentType == null ) )
                        {
                            String isConfirm = ( String ) session.getAttribute ( "isConfirm" );
                            String nonCompanyEmails = null;

                            if( isConfirm == null )
                            {
                                nonCompanyEmails = getNonCompanyEmailIds( to, cc, bcc);
                            }

                            if (( nonCompanyEmails!=null) && (nonCompanyEmails.trim ().length () > 0 ))
                            {
                                errors.put ( "The following e-mails are going out of the company. Please confirm to send them.", null );
                                info.put ( "Emails: ", nonCompanyEmails );

                                session.setAttribute ( "isConfirm", "True" );
                                // get the emails from notification_emails_table
                                request.setAttribute( "psEmailsArray", PackingSlipDAO.loadVendorEmailsForPackingSlip() );

                                String [] vendorMails = PackingSlipDAO.loadVendorEmailsForPackingSlip(); // to fetch the email from  notification_emails_table
                                String vendorEmailsStr   = "";

                                //to load the Vendor Location and Sales Office Comntact person mail ids.
                                int fromLocationId  = packingSlipForm.getShippingFromLocationId();
                                ContactPerson vendorContactperson   = null;
                                psVendorContactPersons = VendorDAO.getAllVendorContactPersonsWithEmails( null, fromLocationId );
                                for ( int i = 0; i < psVendorContactPersons.size() ; i++ )
                                {
                                    vendorContactperson = ( ContactPerson ) psVendorContactPersons.get ( i );
                                    if( vendorContactperson.getIsChecked() )
                                    {
                                        if(vendorContactperson.getEmail() != null)
                                        {
                                            vendorEmailsStr = vendorEmailsStr + vendorContactperson.getEmail() + ", ";
                                        }
                                    }
                                }
                                if( vendorMails != null && vendorMails.length > 0 )
                                {

                                    for(int i=0; i < vendorMails.length; i++)
                                    {
                                        if( vendorMails[i] != null && vendorMails[i].length() >0 )
                                        {
                                                vendorEmailsStr = vendorEmailsStr + vendorMails[i] + ", ";
                                        }
                                    }
                                }
                                if( vendorEmailsStr != null && vendorEmailsStr.length() > 1 )
                                {
                                    vendorEmailsStr = vendorEmailsStr.substring( 0 , vendorEmailsStr.length() - 2 );
                                }
                                request.setAttribute( "vendorEmail", vendorEmailsStr);
                                loadDefaultContactPersonMails( packingSlipForm, request );

                                sendMailForm.setPackingSlipStatus( packingSlipForm.getStatus().trim() );
                                sendMailForm.setDropShippment( packingSlipForm.isDropShippment() );

                                if( packingSlipForm.getIsSample() )
                                {
                                    request.setAttribute("vendorSubjectText", "Dropship Notice : " + packingSlipForm.getLabel() +  " For Sample Sales Order No : " + packingSlipForm.getSalesOrderNumber() );
                                    request.setAttribute("customerSubjectText", "Packing Slip : " + packingSlipForm.getLabel()  + " For Sample Sales Order No : " + packingSlipForm.getSalesOrderNumber());

                                }
                                else
                                {
                                    request.setAttribute("vendorSubjectText", "Dropship Notice : " + packingSlipForm.getLabel() + " For Sales Order No : " + packingSlipForm.getSalesOrderNumber() );
                                    request.setAttribute("customerSubjectText", "Packing Slip : " + packingSlipForm.getLabel()  + " For Sales Order No : " + packingSlipForm.getSalesOrderNumber());
                                }




                                return mapping.findForward ( "success" );
                            }
                        }

                        //here we setting dropshipment=false when customer open's ps and dropshipment=true when vendor open's ps
                        //for getting dropshipment printer friendly for vendor and ps printer friendly for customer
                        if( "customer".equalsIgnoreCase(recipientType) )
                        {
                            packingSlipForm.setDropShippment( false );
                        }
                        else
                        {
                            packingSlipForm.setDropShippment( true );
                        }
                        if( ( vendorMailAttachmentType != null && vendorMailAttachmentType.equalsIgnoreCase("packingslip") ) )
                        {
                            mineType = "PDF";
                        }
                        else if( vendorMailAttachmentType != null && vendorMailAttachmentType.equalsIgnoreCase("shipmentpicknotice") )
                        {
                            mineType = "PDF";
                        }
                        if( "PDF".equalsIgnoreCase( mineType ) )
                        {
                            packingSlipFile = packingSlipAction.getPackingSlipAsPDFFile( host, packingSlipForm, (HashMap) session.getAttribute (SessionKeys.FINAL_INVENTORY_MAP ) ) ;
                        }
                        else
                        {
                            packingSlipFile = packingSlipAction.getPackingSlipAsHtmlFile( host, packingSlipForm, (HashMap) session.getAttribute (SessionKeys.FINAL_INVENTORY_MAP ) ) ;
                        }

						String[] mailAttachments = null;
						boolean sendCommInvoice = false;

						if( "on".equalsIgnoreCase( sendMailForm.getSendCommercialInvoice() ) )
						{
							sendCommInvoice = true;
                            String commercialInvoiceFile = null;

                            if( "PDF".equalsIgnoreCase( mineType ) )
                                commercialInvoiceFile = CommercialInvoiceAction.getCommercialInvoiceAsPDFFile( packingSlipForm.getSalesOrderId()+"", packingSlipForm.getCustomerShippingId()+"", host, packingSlipForm.getLabel() );
                            else
                                commercialInvoiceFile = CommercialInvoiceAction.getCommercialInvoiceAsHtmlFile( packingSlipForm.getSalesOrderId()+"", packingSlipForm.getCustomerShippingId()+"", host );
                            mailAttachments = new String[]{packingSlipFile, commercialInvoiceFile};
                        }
						else
						{
							mailAttachments = new String[] { packingSlipFile };
						}

                        Mailer.send( from, to, cc, bcc, subject, message, mailAttachments, Mailer.CONTENT_TYPE_HTML, false );
						if( sendCommInvoice )
						{
							info.put ( "Packingslip and Commercial Invoices have been sent, successfully", null );
						}
						else
						{
							info.put ( "Packingslip has been sent, successfully", null );
						}

                        session.removeAttribute ( "PSShowAgain" );
                        session.removeAttribute ( "isConfirm" );

						success = true;
					}
					catch ( Exception se )
					{
						success = false;
						String errMessage = se.getMessage();

						if( ( errMessage == null ) || ( errMessage.trim().length() == 0 ) )
						{
							errMessage = "Internal Server Error";
						}
						errors.put( "Sending Failed ", "Could not send Email" );
						se.printStackTrace();
					}
				}
			}
            if( vendorMailAttachmentType != null )
            {
                request.setAttribute("vendorMailAttachmentType", vendorMailAttachmentType);
            }
            return ( mapping.findForward( "sendMailView" ) );
		}
        else if ( "showPSContactPersonDetails".equalsIgnoreCase ( action ) )
        {
            String recipientType = request.getParameter( "recipientType" );
            try
            {
                String value = ( String ) session.getAttribute ( "PSShowAgain" );
                if ( "True".equals ( value ) )
                {
                    psContactPersons = ( ArrayList ) session.getAttribute ( "PSContactPersons" );
                    psVendorContactPersons = ( ArrayList ) session.getAttribute( "PSVendorContactPersons" );
                }
                else
                {
                    SalesOrder  salesOrder          = null;
                    String      salesOrderId        = "-1";
                    int         fromLocationId      = -1;
                    int         contactPersonsSize  = 0;
                    ShippingAdviseForm shippingAdviseForm   = null;
                    PackingSlipForm packingSlipForm         = null;
                    if( user.getUserType() != Constants.USER_TYPE_CHIPTRAC )//When request come from vendor interface
                    {
                        shippingAdviseForm = ( ShippingAdviseForm ) session.getAttribute ( "shippingAdviseForm" );
                        salesOrderId    = shippingAdviseForm.getSalesOrderId() + "";
                        fromLocationId  = shippingAdviseForm.getShippingFromLocationId();
                    }
                    else
                    {
                        packingSlipForm = ( PackingSlipForm ) session.getAttribute ( "packingSlipForm" );
                        salesOrderId    = packingSlipForm.getSalesOrderId() + "";
                        fromLocationId  = packingSlipForm.getShippingFromLocationId();
                    }
                    salesOrder 	= SalesOrderDAO.loadSalesOrder ( salesOrderId , null );

                    if( vendorMailAttachmentType == null )
                    {
                        psContactPersons = CustomerDAO.getAllContactPersonsWithEmails( null , salesOrder );
                        int billingAddressId = SalesOrderDAO.getDefaultBillingAddressId( salesOrder.getCustomerId() );
                        String customerEmail    = CustomerDAO.getAddress( billingAddressId ).getEmail();

                        if( psContactPersons != null ){
                            contactPersonsSize = psContactPersons.size();
                        }
                        ArrayList  userEmailsList = new ArrayList();
                        int userEmailsSize = 0;

                        try
                        {
                            userEmailsList = UserDAO.loadEmailsByType(Constants.USER_NOTIFICATION_EMAIL_TYPE_FOR_PACKING_SLIP);
                        }
                        catch( ScalarException se )
                        {
                            se.getRootCause().printStackTrace();
                            System.out.println( "Exception while retrieving email list");
                        }
                        if ( userEmailsList != null )
                        {
                            userEmailsSize = userEmailsList.size();
                        }
                        String [] vendorMails = PackingSlipDAO.loadVendorEmailsForPackingSlip();

                        if( vendorMails != null )
                        {
                            notificationUserEmailsLength = vendorMails.length;
                        }
                        types = new String[ contactPersonsSize + userEmailsSize + notificationUserEmailsLength + 2 ];
                        int i = 0;
                        if( psContactPersons != null && psContactPersons.size() > 0 )
                        {
                            for ( i = 0; i < psContactPersons.size(); i++ )
                            {
                               ContactPerson contactPerson = ( ContactPerson ) psContactPersons.get ( i );

                               if ( contactPerson.getPackingSlip() )
                               {
                                   contactPerson.setIsChecked ( true );
                               }
                               types[i] = "Contact Person";
                            }
                        }
                        if ( customerEmail != null && !"".equals(customerEmail.trim()) )
                        {
                           ContactPerson customer = new ContactPerson();
                           customer.setContactPerson(salesOrder.getCustomerName());
                           customer.setEmail( customerEmail );
                           psContactPersons.add(customer);
                           types[i++] = "Customer";
                        }
                        ContactPerson notificationUser[] = new ContactPerson[notificationUserEmailsLength];
                        for (int j = 0; j < notificationUserEmailsLength; j++) {
                            notificationUser[j] = new ContactPerson();
                            notificationUser[j].setEmail( vendorMails[j] );
                            notificationUser[j].setIsChecked( true );
                            if( psContactPersons == null )
                            {
                                psContactPersons = new ArrayList();
                            }
                            psContactPersons.add(notificationUser[j]);
                            types[i++] = "Notification";
                        }
                        if ( userEmailsList != null && userEmailsSize > 0 )
                        {
                           for( int j = 0; j < userEmailsSize; j++ )
                           {
                               ContactPerson customer = new ContactPerson();
                               StringTokenizer st = new StringTokenizer ( ( String )userEmailsList.get(j), "/" );
                               String userName = st.nextToken ();
                               String userEmail = st.nextToken ();
                               customer.setContactPerson( userName );
                               customer.setEmail( userEmail );
                               customer.setIsChecked( true );
                               if ( psContactPersons == null )
                               {
                                    psContactPersons = new ArrayList();
                               }
                               psContactPersons.add(customer);
                               types[i++] = "User";
                           }
                        }

                        psVendorContactPersons = VendorDAO.getAllVendorContactPersonsWithEmails( null, fromLocationId );

                        if( psVendorContactPersons != null ){
                            contactPersonsSize = psVendorContactPersons.size();
                        }
                       vtypes = new String[ contactPersonsSize + notificationUserEmailsLength + userEmailsSize + 1 ];
                       int k =0;
                       if( psVendorContactPersons != null )
                       {
                           ContactPerson contactPerson = null;
                           for ( k = 0; k < psVendorContactPersons.size (); k++ )
                           {
                                //vtypes[k] = "Contact Person";
                               contactPerson = ( ContactPerson ) psVendorContactPersons.get(k);
                               vtypes[k] = contactPerson.getContactPersonType() ;
                           }
                       }
                       for (int j = 0; j < notificationUserEmailsLength; j++) {
                            notificationUser[j] = new ContactPerson();
                            notificationUser[j].setEmail( vendorMails[j] );
                            notificationUser[j].setIsChecked( true );
                            if( psVendorContactPersons == null )
                            {
                                psVendorContactPersons = new ArrayList();
                            }
                            psVendorContactPersons.add(notificationUser[j]);
                            vtypes[k++] = "Notification";
                       }
                       if ( userEmailsList != null && userEmailsSize > 0 )
                       {
                           for( int j = 0; j < userEmailsSize; j++ )
                           {
                               ContactPerson customer = new ContactPerson();
                               StringTokenizer st = new StringTokenizer ( ( String )userEmailsList.get(j), "/" );
                               String userName = st.nextToken ();
                               String userEmail = st.nextToken ();
                               customer.setContactPerson( userName );
                               customer.setEmail( userEmail );
                               customer.setIsChecked( true );
                               if( psVendorContactPersons == null )
                               {
                                    psVendorContactPersons = new ArrayList();
                               }
                               psVendorContactPersons.add(customer);
                               vtypes[k++] = "User";
                           }
                        }
                    }
                    else
                    {
                        int customerId = NewSalesOrderDAO.getCustomerID( null, shippingAdviseForm.getSalesOrderId() + "" );
                        ContactPerson contactPerson = null;
                        if( vendorMailAttachmentType.equalsIgnoreCase("shipmentpicknotice") )
                        {
                            psVendorContactPersons = NewPackingSlipDAO.loadAllPackingSlipEmailsList( customerId, shippingAdviseForm.getCustomerShippingId(), shippingAdviseForm.getOdmId(), true );
                            vtypes = new String[ psVendorContactPersons.size() ];
                            for( int j = 0; j < psVendorContactPersons.size() ; j++ )
                            {
                                contactPerson = ( ContactPerson ) psVendorContactPersons.get( j );
                                vtypes[j] = contactPerson.getContactPersonType();
                            }
                        }
                        else
                        {
                            psContactPersons = NewPackingSlipDAO.loadAllPackingSlipEmailsList( customerId, shippingAdviseForm.getCustomerShippingId(), shippingAdviseForm.getOdmId(), false );
                            types = new String[ psContactPersons.size() ];
                            for( int j = 0; j < psContactPersons.size() ; j++ )
                            {
                                contactPerson = ( ContactPerson ) psContactPersons.get( j );
                                types[j] = contactPerson.getContactPersonType();
                            }
                        }
                    }
                   session.setAttribute ("types",types);
                   session.setAttribute ("vtypes",vtypes);
                }
            }
            catch ( ScalarException e )
            {
                e.printStackTrace ();
            }

            if( vendorMailAttachmentType == null )
            {
                request.setAttribute ( "PSContactPersons", psContactPersons );
                request.setAttribute ( "PSVendorContactPersons", psVendorContactPersons );
            }
            else
            {
                if( vendorMailAttachmentType.equalsIgnoreCase("shipmentpicknotice") )
                {
                    request.setAttribute ( "PSVendorContactPersons", psVendorContactPersons );
                }
                else
                {
                    request.setAttribute ( "PSContactPersons", psContactPersons );
                }
            }
            session.setAttribute ( "PSShowAgain", "False" );
            session.setAttribute ( "recipientType",recipientType);
            return ( mapping.findForward ( "showPSContactPersons" ) );
        }
        else if ( "displayPrvMailIds".equalsIgnoreCase ( action ) )
        {
            String recipientType = (String)session.getAttribute("recipientType");
            try
            {
                String      salesOrderId        = "-1";
                int         fromLocationId      = -1;
                if( user.getUserType() != Constants.USER_TYPE_CHIPTRAC )//When request come from vendor interface
                {
                    ShippingAdviseForm shippingAdviseForm = ( ShippingAdviseForm ) session.getAttribute ( "shippingAdviseForm" );
                    salesOrderId    = shippingAdviseForm.getSalesOrderId() + "";
                    fromLocationId  = shippingAdviseForm.getShippingFromLocationId();
                }
                else
                {
                    PackingSlipForm packingSlipForm = ( PackingSlipForm ) session.getAttribute ( "packingSlipForm" );
                    salesOrderId    = packingSlipForm.getSalesOrderId() + "";
                    fromLocationId  = packingSlipForm.getShippingFromLocationId();
                }
                SalesOrder salesOrder 	= SalesOrderDAO.loadSalesOrder ( salesOrderId , null );
                psContactPersons = CustomerDAO.getAllContactPersonsWithEmails(null, salesOrder );
                int billingAddressId = SalesOrderDAO.getDefaultBillingAddressId( salesOrder.getCustomerId() );
                String customerEmail    = CustomerDAO.getAddress( billingAddressId ).getEmail();
                ArrayList  userEmailsList = new ArrayList();
                int userEmailsSize = 0;

                try
                {
                    userEmailsList = UserDAO.loadEmailsByType(Constants.USER_NOTIFICATION_EMAIL_TYPE_FOR_PACKING_SLIP);
                }
                catch( ScalarException se )
                {
                    se.getRootCause().printStackTrace();
                    System.out.println( "Exception while retrieving email list");
                }
                if ( userEmailsList != null )
                {
                    userEmailsSize = userEmailsList.size();
                }
                for ( int i = 0; i < psContactPersons.size (); i++ )
                {
                    ContactPerson contactPerson = ( ContactPerson ) psContactPersons.get ( i );

                    if ( contactPerson.getPackingSlip() )
                    {
                        contactPerson.setIsChecked ( true );
                    }
                }
                if ( customerEmail != null && !"".equals(customerEmail.trim()) )
                {
                   ContactPerson customer = new ContactPerson();
                   customer.setContactPerson(salesOrder.getCustomerName());
                   customer.setEmail( customerEmail );
                   psContactPersons.add(customer);
               }
               String [] vendorMails = PackingSlipDAO.loadVendorEmailsForPackingSlip();
               if( vendorMails != null )
               {
                    notificationUserEmailsLength = vendorMails.length;
               }
               ContactPerson notificationUser[] = new ContactPerson[notificationUserEmailsLength];
               for (int j = 0; j < notificationUserEmailsLength; j++) {
                    notificationUser[j] = new ContactPerson();
                    notificationUser[j].setEmail( vendorMails[j] );
                    notificationUser[j].setIsChecked( true );
                    psContactPersons.add(notificationUser[j]);
               }
               if ( userEmailsList != null && userEmailsSize > 0 )
               {
                  for( int j = 0; j < userEmailsSize; j++ )
                  {
                      ContactPerson customer = new ContactPerson();
                      StringTokenizer st = new StringTokenizer ( ( String )userEmailsList.get(j), "/" );
                      String userName = st.nextToken ();
                      String userEmail = st.nextToken ();
                      customer.setContactPerson( userName );
                      customer.setEmail( userEmail );
                      customer.setIsChecked( true );
                      psContactPersons.add(customer);
                  }
               }
                psVendorContactPersons = VendorDAO.getAllVendorContactPersonsWithEmails( null, fromLocationId );
                for (int j = 0; j < notificationUserEmailsLength; j++) {
                    notificationUser[j] = new ContactPerson();
                    notificationUser[j].setEmail( vendorMails[j] );
                    notificationUser[j].setIsChecked( true );
                    psVendorContactPersons.add(notificationUser[j]);
                }
                if ( userEmailsList != null && userEmailsSize > 0 )
                {
                   for( int j = 0; j < userEmailsSize; j++ )
                   {
                       ContactPerson customer = new ContactPerson();
                       StringTokenizer st = new StringTokenizer ( ( String )userEmailsList.get(j), "/" );
                       String userName = st.nextToken ();
                       String userEmail = st.nextToken ();
                       customer.setContactPerson( userName );
                       customer.setIsChecked( true );
                       customer.setEmail( userEmail );
                       psVendorContactPersons.add(customer);
                   }
                }
                if("customer".equals(recipientType) )
                {
                    for ( int i = 0; i < psContactPersons.size (); i++ )
                    {
                        ContactPerson contactPerson = ( ContactPerson ) psContactPersons.get ( i );

                        if ( request.getParameter ( "selectedValue" + i ) != null )
                        {
                            contactPerson.setIsChecked ( true );
                        }
                        else
                        {
                            contactPerson.setIsChecked ( false );
                        }
                    }
                }
                else
                {
                    for ( int i = 0; i < psVendorContactPersons.size (); i++ )
                    {
                        ContactPerson contactPerson = ( ContactPerson ) psVendorContactPersons.get ( i );

                        if ( request.getParameter ( "selectedValue" + i ) != null )
                        {
                            contactPerson.setIsChecked ( true );
                        }
                        else
                        {
                            contactPerson.setIsChecked ( false );
                        }
                    }
                }
                session.setAttribute ( "PSContactPersons", psContactPersons );
                session.setAttribute ( "PSVendorContactPersons", psVendorContactPersons );
                session.setAttribute ( "PSShowAgain", "True" );
            }
            catch ( Exception se )
            {
                System.out.println ( "Exception while loading Packing Slip acknowledgement emails.. " );
            }
            return ( mapping.findForward ( "success" ) );
        }

		PackingSlipForm packingSlipForm = null;
		try
		{
			String vendorEmailsStr   = "";
            String subject           = "";
			packingSlipForm = NewPackingSlipDAO.loadPackingSlipById( customerShippingId );
            String [] vendorMails = PackingSlipDAO.loadVendorEmailsForPackingSlip(); // to fetch the email from  notification_emails_table
            int fromLocationId  = packingSlipForm.getShippingFromLocationId();
            ContactPerson vendorContactperson   = null;

            ArrayList  userEmailsList = new ArrayList();
            int userEmailsLength = 0;
            StringBuffer userMailsStrBuff = new StringBuffer();
            String userMailsStr = "";

            if( ( vendorMailAttachmentType == null ) )
            {
                psVendorContactPersons = VendorDAO.getAllVendorContactPersonsWithEmails( null, fromLocationId );
                try
                {
                    userEmailsList = UserDAO.loadEmailsByType(Constants.USER_NOTIFICATION_EMAIL_TYPE_FOR_PACKING_SLIP);
                }
                catch( ScalarException se )
                {
                    se.getRootCause().printStackTrace();
                    System.out.println( "Exception while retrieving email list");
                }
                if( userEmailsList != null )
                {
                   userEmailsLength = userEmailsList.size();
                   for( int k = 0; k < userEmailsLength; k++ )
                   {
                       StringTokenizer st = new StringTokenizer ( ( String )userEmailsList.get(k), "/" );
                       String userName = st.nextToken ();
                       String userEmail = st.nextToken ();
                       userMailsStrBuff = userMailsStrBuff.append( userEmail ).append(", ");
                   }
                }
                if( userMailsStrBuff != null && userMailsStrBuff.length() > 1 )
                {
                    userMailsStr = userMailsStrBuff.substring( 0 , userMailsStrBuff.length() - 2 );
                }
                if( psVendorContactPersons != null &&  psVendorContactPersons.size() > 0 )
                {
                    for ( int i = 0; i < psVendorContactPersons.size() ; i++ )
                    {
                        vendorContactperson = ( ContactPerson ) psVendorContactPersons.get ( i );
                        if( vendorContactperson.getIsChecked() )
                        {
                            if(vendorContactperson.getEmail() != null)
                            {
                                vendorEmailsStr = vendorEmailsStr + vendorContactperson.getEmail() + ", ";
                            }
                        }
                    }
                }
                if( vendorMails != null && vendorMails.length > 0 )
                {
                    for(int i=0; i < vendorMails.length; i++)
                    {
                        if( vendorMails[i] != null && vendorMails[i].length() >0 )
                        {
                            vendorEmailsStr = vendorEmailsStr + vendorMails[i] + ", ";
                        }
                    }
                }
                if( vendorEmailsStr != null && vendorEmailsStr.length() > 1 )
                {
                    vendorEmailsStr = vendorEmailsStr.substring( 0 , vendorEmailsStr.length() - 2 );
                }
            }

            if(  vendorMailAttachmentType != null && vendorMailAttachmentType.equalsIgnoreCase("shipmentpicknotice") )
            {
                sendMailForm.setRecipientType("vendor");//to set the reciepeint type by default to customer
            }
            else
            {
                sendMailForm.setRecipientType("customer");//to set the reciepeint type by default to customer
            }
            sendMailForm.setPackingSlipStatus( packingSlipForm.getStatus().trim() );
            sendMailForm.setDropShippment( packingSlipForm.isDropShippment() );

            subject = "Packing Slip : " + packingSlipForm.getLabel();//default reciepeint type is customer

            if( packingSlipForm.getIsSample() )
            {
                request.setAttribute("vendorSubjectText", "Dropship Notice : " + packingSlipForm.getLabel() +  " For Sample Sales Order No : " + packingSlipForm.getSalesOrderNumber() );
                request.setAttribute("customerSubjectText", "Packing Slip : " + packingSlipForm.getLabel()  + " For Sample Sales Order No : " + packingSlipForm.getSalesOrderNumber());

            }
            else
            {
                request.setAttribute("vendorSubjectText", "Dropship Notice : " + packingSlipForm.getLabel() + " For Sales Order No : " + packingSlipForm.getSalesOrderNumber() );
                request.setAttribute("customerSubjectText", "Packing Slip : " + packingSlipForm.getLabel()  + " For Sales Order No : " + packingSlipForm.getSalesOrderNumber());
            }


            sendMailForm.setSubject(subject);
            if(ConfigManager.isCIIncludePackingslip())
            {
                sendMailForm.setSendCommercialInvoice("on");
            }
            else
            {
                sendMailForm.setSendCommercialInvoice("");
            }

            if( vendorMailAttachmentType == null )
            {
                loadDefaultContactPersonMails( packingSlipForm, request ); //Added by varma to load the default contact person mail ids
                request.setAttribute( "vendorEmail", vendorEmailsStr );
                request.setAttribute( "userMails", userMailsStr );
            }
            else
            {
                String emailIdsString = "";
                int customerId = NewSalesOrderDAO.getCustomerID( null, packingSlipForm.getSalesOrderId() + "" );
                if( vendorMailAttachmentType.equalsIgnoreCase("shipmentpicknotice") )
                {
                    emailIdsString = NewPackingSlipDAO.loadAllPackingSlipEmails( customerId , packingSlipForm.getCustomerShippingId(), packingSlipForm.getOdmId(), true );
                    request.setAttribute( "vendorEmail", emailIdsString );
                }
                else
                {
                    emailIdsString = NewPackingSlipDAO.loadAllPackingSlipEmails( customerId , packingSlipForm.getCustomerShippingId(), packingSlipForm.getOdmId(), false );
                    request.setAttribute( "psEmails", emailIdsString );
                }
            }

        }
		catch( ScalarException se )
		{
		    System.out.println( "Exception while loading packingslip vendor emails.. ");
			se.getRootCause().printStackTrace();
		}
		//to remove 'PSShowAgain' object from session because we get exception,
        //actually this is used to display the previous selected contact persons emailds for particular Packing Slip
        session.removeAttribute ( "PSShowAgain" );
        session.removeAttribute ( "isConfirm" );
        
        sendMailForm.setFromUser( ConfigManager.getFromEmailId(Constants.FROM_EMAIL_PACKINGSLIP_GROUP_NAME ) );
		request.setAttribute( "sendMailForm" , sendMailForm );

		return( mapping.findForward( "success" ) );
	}

    //***************to get the Non Company Email Ids********************
    private String getNonCompanyEmailIds(String to, String cc, String bcc) throws ScalarException, AddressException
    {
        String sysAdminEmail = ConfigManager.getSysAdminEmail ();
        String companyEmailId = sysAdminEmail.substring ( sysAdminEmail.indexOf ( "@" ) + 1, sysAdminEmail.length () );
        String emailIds = "";

        to = Mailer.getNotifiableEmails ( to, false );
        cc = Mailer.getNotifiableEmails ( cc, false );
        bcc = Mailer.getNotifiableEmails ( bcc, false );

        InternetAddress[] toAddress = null;

        String allEmails = "";
        if( to == null )
        {
            to = "";
        }
        if( cc == null )
        {
            cc = "";
        }
        if( bcc == null )
        {
            bcc = "";
        }
        allEmails = to + " , " + cc + " , " + bcc;

        if ( allEmails != null )
        {
            toAddress = InternetAddress.parse ( allEmails );
            for ( int i = 0; i < toAddress.length; i++ )
            {
                if(( toAddress[i] != null ) && ( toAddress[i].toString().trim().length()>0 ))
                {
                    InternetAddress temp = toAddress[i];
                    String address = temp.getAddress ();
                    if ( address.indexOf ( companyEmailId ) == -1 )
                    {
                        emailIds = emailIds + temp.getAddress () + "; ";
                    }
                }
            }
        }
        return emailIds;
    }

//to load the default mail ids of contact persons for PS and CommInv
    private void loadDefaultContactPersonMails ( PackingSlipForm packingSlipForm, HttpServletRequest request ) throws ScalarException
    {
        ContactPerson cperson   = null;
        try
        {
            SalesOrder salesOrder 	 = SalesOrderDAO.loadSalesOrder ( packingSlipForm.getSalesOrderId() + "" , null );
            ArrayList contactPersons = CustomerDAO.getAllContactPersonsWithEmails ( null, salesOrder );
            int contactPersonsSize   = contactPersons.size ();
            String psEmails          = "";
            String commEmails        = "";

            for ( int i = 0; i < contactPersonsSize; i++ )
            {
                cperson = ( ContactPerson ) contactPersons.get ( i );
                if( cperson.getPackingSlip() )                            //to load the packing slip mail ids
                {
                    if(cperson.getEmail() != null)
                    {
                        psEmails = psEmails + cperson.getEmail() + ", ";
                    }
                }
                if( cperson.getCommerInvoice() )   //to load the commercial invoice mail ids only
                {
                    if( cperson.getEmail() != null )
                    {
                        commEmails = commEmails + cperson.getEmail() + ", " ;
                    }
                }
            }
            if( psEmails != null && psEmails.length() > 1 )
            {
                psEmails = psEmails.substring( 0 , psEmails.length() - 2 );
            }
            if( commEmails != null && commEmails.length() > 1 )
            {
                commEmails = commEmails.substring( 0 , commEmails.length() - 2 );
            }
			request.setAttribute( "psEmails", psEmails );
            request.setAttribute( "commEmails",commEmails );

        }
        catch ( ScalarException se)
        {
            throw new ScalarException ( "Error While Loading the Default Mail Ids  " );
        }
    }
}